package com.tsingteng.cosfun.ui.cosfun;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PowerManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.util.Pair;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.bean.OpusBean;
import com.tsingteng.cosfun.common.BroadcastManager;
import com.tsingteng.cosfun.common.Config;
import com.tsingteng.cosfun.common.Constant;
import com.tsingteng.cosfun.helper.ActivityManagers;
import com.tsingteng.cosfun.ui.mine.HomeMineFragment;
import com.tsingteng.cosfun.utils.NotchUtil;
import com.tsingteng.cosfun.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

public class PlayActivity extends FragmentActivity {
    private String TAG = this.getClass().getSimpleName();
    ViewPager viewpager = null;
    MyFragmentStatePagerAdapter adapter = null;
    List<Pair<String, Fragment>> mFragmentPair = null;
    List<OpusBean> coverImgUrl;
    int currentPosition = 0;
    int type;
    int parentId;
    int position;
    int pageNo;
    long userId;
    String showType;
    String mFound;
    String sortType;
    int pageSize;
    String mListData;
    private PowerManager pm;
    private PowerManager.WakeLock wl;
    private VideoplayFragment videoplayFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            savedInstanceState.remove(Config.FRAGMENTS_TAG);
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_cos);
        //管理屏幕常亮状态
        pm = (PowerManager) getSystemService(POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                getResources().getString(R.string.app_name));
        bright();
        ActivityManagers.getInstance().addActivity(this);
        ActivityManagers.getInstance().setPlayList(this);
        NotchUtil.setWindowTrans(this, true, false);
        Intent intent = this.getIntent();
        if (intent == null) {
            Toast.makeText(this, "参数有误", Toast.LENGTH_SHORT).show();
            this.finish();
        }
          mFound=intent.getStringExtra(Constant.FOUND);
        if (TextUtils.isEmpty(mFound)) {
            type = intent.getIntExtra("type", -1);
            parentId = intent.getIntExtra("id", 1);

//        position = intent.getIntExtra("position", -1);
            position = intent.getIntExtra("position", 0);
            pageNo = intent.getIntExtra("pageNo", 1);
            showType = intent.getStringExtra("showType");
            userId = intent.getLongExtra("userId", 0L);

            if (type == -1 || parentId == -1) {
                Toast.makeText(this, "参数有误", Toast.LENGTH_SHORT).show();
                this.finish();
            }
        }else{
            if ("found".equals(mFound)) {
                position = intent.getIntExtra(Constant.POSITION, 0);
                pageNo = intent.getIntExtra(Constant.PAGENO, 1);
                parentId = intent.getIntExtra(Constant.ID, 1);
                sortType = intent.getStringExtra(Constant.SORTTYPE);
                pageSize = intent.getIntExtra(Constant.PAGESIZE, 1);
                mListData = intent.getStringExtra(Constant.DATA);
            }else if ("at_video".equals(mFound)){
                coverImgUrl = (List<OpusBean>) intent.getSerializableExtra(Constant.COVERIMGURL);
                position = intent.getIntExtra(Constant.POSITION, 0);
            }
        }
        initView();
    }

    public void changeId(int id) {
        if (mFragmentPair.get(0).first.equals("play_awkward")) {
//            ((AwkwardFragment) (mFragmentPair.get(0).second)).changeId(id);
        }
        if (mFragmentPair.get(2).first.equals("play_opus")) {
//            ((HomeMineFragment) (mFragmentPair.get(2).second)).changeId(id);
        }
    }


    /**
     * 屏幕常亮
     */
    public void bright() {
        try {
            wl.acquire();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void initView() {
        viewpager = findViewById(R.id.cos_viewpager);
        mFragmentPair = new ArrayList<Pair<String, Fragment>>();
        videoplayFragment = new VideoplayFragment();
        if (TextUtils.isEmpty(mFound)) {
            videoplayFragment.setDataType(type, parentId, position, pageNo, showType, userId);
        } else {
            if ("found".equals(mFound)) {
                videoplayFragment.setDataFound(mFound, parentId, position, pageNo, sortType, pageSize,mListData);
            } else if ("at_video".equals(mFound)) {
                videoplayFragment.setFoundVideo(mFound, coverImgUrl, position);
            }
        }
//        Pair awkwardPair = new Pair("play_awkward", new AwkwardFragment());
        Pair opusPair = new Pair("play_opus", videoplayFragment);
        HomeMineFragment homeMineFragment = new HomeMineFragment();
        homeMineFragment.setBackLisenter(backLisenter);
        Pair personalPair = new Pair("play_personal", homeMineFragment);
//        mFragmentPair.add(awkwardPair);
        mFragmentPair.add(opusPair);
        mFragmentPair.add(personalPair);

        adapter = new MyFragmentStatePagerAdapter(getSupportFragmentManager(), mFragmentPair);
        viewpager.setAdapter(adapter);
        viewpager.setCurrentItem(currentPosition);
        viewpager.setOffscreenPageLimit(2);
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentPosition = position;
                switch (currentPosition) {
                    case 0:
//                        if (mFragmentPair.get(0).first.equals("play_awkward")) {
//                            ((AwkwardFragment) (mFragmentPair.get(0).second)).getData();
//                            ((AwkwardFragment) (mFragmentPair.get(0).second)).playVideo(-1);
//                        }
                        if (mFragmentPair.get(0).first.equals("play_opus")) {
                            ((VideoplayFragment) (mFragmentPair.get(0).second)).play();
                        }
                        break;
                    case 1:
//                        if (mFragmentPair.get(0).first.equals("play_awkward")) {
//                            ((AwkwardFragment) (mFragmentPair.get(0).second)).onPause();
//                        }

                        if (mFragmentPair.get(0).first.equals("play_opus")) {
                            ((VideoplayFragment) (mFragmentPair.get(0).second)).onPause();
                        }
                        if (mFragmentPair.get(1).first.equals("play_personal")) {
                            ((HomeMineFragment) (mFragmentPair.get(1).second)).refreshData();
                            ((HomeMineFragment) (mFragmentPair.get(1).second)).goneButtomView(View.GONE);
                        }
                        break;
                    case 2:
                        if (mFragmentPair.get(1).first.equals("play_opus")) {
                            ((VideoplayFragment) (mFragmentPair.get(1).second)).onPause();
                        }
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
//        videoListPresenter = new VideoListPresenter(this);
//        videoListPresenter.getXiPuVideoListList("80", "1");
    }

    @Override
    public void onResume() {
        super.onResume();
//        if (currentPosition == 0) {
//            if (mFragmentPair.get(0).first.equals("play_awkward")) {
//                ((AwkwardFragment) (mFragmentPair.get(0).second)).onResume();
//            }
//        }
        if (currentPosition == 0) {
            if (mFragmentPair.get(currentPosition).first.equals("play_opus")) {
                ((VideoplayFragment) (mFragmentPair.get(currentPosition).second)).onPlay();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
//        if (currentPosition == 0) {
//            if (mFragmentPair.get(0).first.equals("play_awkward")) {
//                ((AwkwardFragment) (mFragmentPair.get(0).second)).onPause();
//            }
//        }
        if (currentPosition == 1) {
            if (mFragmentPair.get(currentPosition).first.equals("play_opus")) {
                ((VideoplayFragment) (mFragmentPair.get(currentPosition).second)).onPause();
            }
        }
    }

    public class MyFragmentStatePagerAdapter extends FragmentStatePagerAdapter {

        private List<Pair<String, Fragment>> mFragmentPair;

        public MyFragmentStatePagerAdapter(FragmentManager fm, List<Pair<String, Fragment>> mFragmentPair) {
            super(fm);
            this.mFragmentPair = mFragmentPair;
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentPair.get(position).second;
        }

        /**
         * adapter.notifyDataSetChanged()的时候，ViewPager会去查询到底哪个位置有改变，
         * return PagerAdapter.POSITION_NONE; 就是告诉所有的View已经变化，从而达到刷新的目的
         *
         * @param object
         * @return
         */
        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
            //  return super.getItemPosition(object);
        }

        @Override
        public int getCount() {
            return mFragmentPair.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentPair.get(position).first;
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }
    }

    HomeMineFragment.BackLisenter backLisenter = new HomeMineFragment.BackLisenter() {
        @Override
        public void back() {
            viewpager.setCurrentItem(0);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (currentPosition == 1) {
                    viewpager.setCurrentItem(0);
                    return true;
                }
               String isBroad = videoplayFragment.getIsBroad();
                if (!TextUtils.isEmpty(isBroad)){
                    BroadcastManager.getInstance(this).sendBroadcast(Constant.REFRESH,isBroad);
                }
                BroadcastManager.getInstance(this).sendBroadcast(Constant.BACK,"back");
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManagers.getInstance().finishActivity(this);
    }
}
